local list = ngx.shared.black_list -- lua 本地缓存，进程共享
local black_list = {}

local count_prefix = "count_"
local black_list_prefix = "black_"
local threshold = 3

-- 检查用户是否在黑名单内
function black_list.contains(user_id) 
    local value = list:get(black_list_prefix..user_id)
    if value == nil then
        ngx.log(ngx.ERR, user_id.." not in black list")
        return false
    end
    ngx.log(ngx.ERR, user_id.." in black list")
    return true
end

-- 生成黑名单并返回用户是否在黑名单内
function black_list.generate(user_id)
    -- 参数1 key，参数2 步长，参数3 默认值，参数4 过期时间 1s
    -- 返回值 增加后结果
    local count = list:incr(count_prefix..user_id, 1, 0, 1)
    if count > threshold then
        ngx.log(ngx.ERR, user_id.." add to black list")
        -- 添加到黑名单 15 秒
        local suc, error = list:set(black_list_prefix..user_id, 1, 15)
        if not suc then
            return false
        end
        return true
    end
end

return black_list